import config from './config'
let BaceUrl = config.baseUrl

function setRequest(url, method, data) {
	uni.showLoading();
	let header = {
		// "content-type": "application/x-www-form-urlencoded",
		"Authori-zation": ''
	}
	let token = uni.getStorageSync('token');
	if (token) {
		header = {
			"Authori-zation": token
			// "content-type": "application/x-www-form-urlencoded"
		}
	}
	var promise = new Promise((resolve, reject) => {
		var that = this;
		uni.request({
			url: BaceUrl + 'api/front/' + url,
			data,
			method,
			header,
			success: (res) => {
				// console.log(res, "res---")
				uni.hideLoading();
				if (res.data.code === 200) {
					resolve(res.data);
				} else {
					resolve(res.data);
					if (res.data.code === 401) {
						if(url === 'user') {
							
						} else {
							uni.showModal({
								title: '提示',
								content: '当前页面或功能需登录后体验，请先登录',
								success: (t) => {
									if(t.confirm) {
										uni.navigateTo({
											url: '/pages/login'
										})
									}
								}
							})
						}
					} else if (res.data.code === 500) {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						});
					} else {
						// if (res.data.message) {
						// 	uni.showToast({
						// 		title: res.data.message,
						// 		icon: 'none'
						// 	});
						// }
					}
					return
				}
			},
			fail: function(e) {
				uni.hideLoading();
				reject("网络出错,连接失败:", JSON.stringify(e));
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
	return promise;
}

function getRequest(url, data) {
	return setRequest(url, "GET", data);
}

function postRequest(url, data) {
	return setRequest(url, "POST", data);
}

function putRequest(url, data) {
	return setRequest(url, "PUT", data);
}

function deleteRequest(url, data) {
	return setRequest(url, "DELETE", data);
}

module.exports = {
	get: getRequest,
	post: postRequest,
	put: putRequest,
	delete: deleteRequest,
};